//
//  AIGirlSetAgeViewController.swift
//  AIGirl
//
//  Created by Rae on 2024/1/16.
//

import UIKit

class AIGirlSetAgeViewController: AIGirlBaseViewController {

    private lazy var backButton = c_make_ex(UIButton.self)
        .image("AIGirl_Signin_back").end()
    private var sliderView = AIGirlMeansSliderView()
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white).font(22.font_bold).alignment(.center)
        .text("Pick your girl").end()
    private lazy var desLabel = c_make_ex(UILabel.self)
        .color(.white).font(17.font_medium).alignment(.center)
        .text("How old is your sweetheart?").end()
    private lazy var selView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.31)).corner(30).border("#C027FF", width: 2).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: MateKingAgeFlowLayout())
    private lazy var nextButton = c_make_ex(AIGirlSubmitButton.self)
        .color(.white).font(21.font_bold).corner(20)
        .text("Next").end()
    private var dataArray: [AIGirlSignInAgeModel] = {
        var data = [AIGirlSignInAgeModel]()
        for index in 0..<43 {
            let age = String(index + 18)
            var isSel = false
            if index == 0 {
                isSel = true
            }
            let model = AIGirlSignInAgeModel(age: age,isSel: isSel)
            data.append(model)
        }
        return data
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.subviews{
            backButton
            sliderView
            titleLabel
            desLabel
            selView
            collectionView
            nextButton
        }
        
        backButton.leading(15).top(.statusHeight).size(30)
        sliderView.leading(37.5).trailing(37.5).height(4.5)
        sliderView.Top == backButton.Bottom + 12
        titleLabel.leading(15).trailing(15)
        titleLabel.Top == sliderView.Bottom + 55
        desLabel.leading(15).trailing(15)
        desLabel.Top == titleLabel.Bottom + 65
        selView.size(60).centerHorizontally()
        collectionView.leading(0).trailing(0).height(60)
        collectionView.Top == desLabel.Bottom + 45
        selView.CenterY == collectionView.CenterY
        nextButton.leading(38).trailing(38).height(50).bottom(.safe_bottom + 60)
        
        sliderView.value = 50
        
        collectionView.style { v in
            v.backgroundColor = .clear
            v.register(AIGirlAgeItem.self, forCellWithReuseIdentifier: AIGirlAgeItem.description())
            let margin = (CGFloat.screenWidth - 60) / 2
            v.contentInset = UIEdgeInsets(top: 0, left: margin, bottom: 0, right: margin)
            v.showsHorizontalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }
        nextButton.addTarget(self, action: #selector(clickNextButton), for: .touchUpInside)
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
    }
    
    @objc private func clickNextButton() {
        
        var userAge: Int = 0
        for model in dataArray {
            if model.isSel {
                userAge = Int(model.age) ?? 0
                UserDefaultsManager.setString(model.age, forKey: .grilAge)
            }
        }
        let nameStr = UserDefaultsManager.getString(forKey: .userName) ?? ""
        self.request.start(.RegisterInfo(name: nameStr, age: userAge, gender: 1)) { result in
            if result.isSuccessful {
                UserDefaultsManager.setInt(3, forKey: .currentPage)
                self.navigationController?.pushViewController(AIGirlUserInfoChooseViewController(), animated: true)
            }
        }        
    }

//    @objc override func clickBackButton() {
//        self.navigationController?.popViewController(animated: true)
//    }
}

extension AIGirlSetAgeViewController: UICollectionViewDelegate, UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: AIGirlAgeItem.description(), for: indexPath) as? AIGirlAgeItem else { return UICollectionViewCell() }
        item.model = dataArray[indexPath.row]
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        var models = [AIGirlSignInAgeModel]()
        dataArray.forEach { model in
            var itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        dataArray = models
        collectionView.reloadData()
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            let scrollToScrollStop = !scrollView.isTracking && !scrollView.isDragging && !scrollView.isDecelerating
            if scrollToScrollStop {
                scrollViewDidEndScrollWithScrollView(scrollView)
            }
        }
        
        func scrollViewDidEndScrollWithScrollView(_ scrollView: UIScrollView) {
            if scrollView == collectionView {
                let centerPoint = CGPoint(x: collectionView.frame.size.width / 2 + scrollView.contentOffset.x, y: collectionView.frame.size.height / 2 + scrollView.contentOffset.y)
                if let indexPath = collectionView.indexPathForItem(at: centerPoint) {
                    var models = [AIGirlSignInAgeModel]()
                    dataArray.forEach { model in
                        var itemModel = model
                        itemModel.isSel = false
                        models.append(itemModel)
                    }
                    models[indexPath.row].isSel = true
                    dataArray = models
                    collectionView.reloadData()
                }
            }
        }
}


class AIGirlAgeItem: UICollectionViewCell {
    
    private lazy var titleLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.6)).font(20.font_semiBold).alignment(.center).end()
    private lazy var selView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.31)).corner(30).border("#FD3B77", width: 2).end()
    
    var model: AIGirlSignInAgeModel? {
        didSet{
            guard let md = model else { return }
            isSel = md.isSel
//            selView.isHidden = !md.isSel
            titleLabel.text = md.age
        }
    }
    
    var isSel: Bool = false {
        didSet {
            titleLabel.textColor = isSel ? .white : .white.alpha(0.6)
        }
    }
            
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.subviews {
            selView
            titleLabel
        }
        selView.isHidden = true
        selView.fillContainer()
        titleLabel.fillContainer()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

